import datetime
import os
import re
import threading
import requests_html
from queue import Queue
#https://www.700ko.com/vodtype/145.html
#前缀https://qq.com-ixx-iqiyi.com/1000k/hls/index.m3u8
#1000k/hls/index.m3u8
#https://qq.com-ixx-iqiyi.com/1000k/hls/43a8a247a1e000000.ts
#"url":"https:\/\/youku.com-jy-youku.com\/20200414\/5813_b38bec48\/index.m3u8"
#思路，获取index.m3u8,使用正则表达式，读取m3u8内容，获取ts地址，多线程get获取，并下载到本地保存，然后ffmpeg进行拼接。
# 预下载，获取m3u8文件，读出ts链接，并写入文档
def down():
    #下载所有m3u8链接
    html:requests_html.HTMLSession=requests_html.HTMLSession()
    res:requests_html.HTML=html.get("https://www.700ko.com/vodplay/412370-1-1.html").html
    htmlcontent=res.full_text
    res:str=re.findall(r'"url":"((.*?)index.m3u8)"',htmlcontent)
    print(res)
    m3u8Url=res[0][0].replace("\\","")
    baseUrl=res[0][1].replace("\\","")
    bm3= html.get(m3u8Url).content
    m3u8real=bm3.decode().split('\n')[-1]
    realm3u8url=baseUrl+m3u8real
    #解析m3u8内容
    print(realm3u8url)
    baseUrl2=realm3u8url[:-10]
    print(baseUrl2)
    finalm3u8=html.get(realm3u8url).content.decode()
    finalm3u8list=finalm3u8.split('\n')
    with open("cache/index.m3u8",'w') as f:
        f.write(finalm3u8)
    m3u8list=[]
    for line in finalm3u8list:
        if '.ts' in line:
            m3u8list.append(line)
    m3u8urllist=[baseUrl2+x for x in m3u8list]
    ts_queue=Queue(maxsize=1000)
    for url in m3u8urllist:
        ts_queue.put(url)
    return ts_queue
# 线程模式，执行线程下载
def run(ts_queue):
    tt_name = threading.current_thread().getName()
    while not ts_queue.empty():
        url = ts_queue.get()
        html: requests_html.HTMLSession = requests_html.HTMLSession()
        r = html.get(url)
        filename =re.findall('/([^/]*?.ts)', url)[0]
        with open('cache/' + filename, 'wb') as fp:
            fp.write(r.content)
        print(tt_name + " " + filename + ' 下载成功')
# 视频合并方法，使用ffmpeg
def merge(concatfile, name):
    try:
        path = 'cache/' + name + '.mp4'
        command = f'ffmpeg  -i {concatfile} -vcodec copy -acodec copy -absf aac_adtstoasc {name}'
        os.system(command)
        print('视频合并完成')
    except:
        print('合并失败')
if __name__ == '__main__':
    merge("cache/index.m3u8",'cache/1.mp4')
    # start = datetime.datetime.now().replace(microsecond=0)
    # if not os.path.exists("cache/"):
    #     os.makedirs("cache/")
    # ts_queue=down()
    # # s,concatfile = down()
    # # # print(s,concatfile)
    # threads = []
    # for i in range(15):
    #   t = threading.Thread(target=run, name='th-'+str(i), kwargs={'ts_queue': ts_queue})
    #   threads.append(t)
    # for t in threads:
    #   t.start()
    # for t in threads:
    #   t.join()
    # end = datetime.datetime.now().replace(microsecond=0)
    # print('下载耗时：' + str(end - start))
    # over = datetime.datetime.now().replace(microsecond=0)
    # print('合并耗时：' + str(over - end))
